package com.ludomancy.gamelib;


public class ProbabilityDistributor
{
	private int[] ranges;
	public int sum;
	public ProbabilityDistributor(int[] distribution)
	{
		ranges = new int[distribution.length+1];
		int accum = distribution[0];
		ranges[0] = 0;
		for(int ndx = 1 ; ndx != distribution.length ; ndx++)
		{
			ranges[ndx] = accum-1;
			accum += distribution[ndx];
		}
		ranges[ranges.length-1] = accum-1;
		sum = accum;
	}
    
	// might return -1 if no event makes sense
    public int getRandomEvent()
    {
    	if(sum == 0)
    	{
    		return -1;
    	}
        return getEventForValue(Randomizer.getRandom(0,sum-1));
    }
	
	public int getEventForValue(int value)
	{
		for(int ndx = 0 ; ndx != ranges.length-1 ; ndx++)
		{
			if( value >= ranges[ndx] && value <= ranges[ndx+1])
				return ndx;
		}
		throw new RuntimeException("ProbDistribution invalid value");
	}
}
